<template>
    <div>
        <!-- 面包屑导航 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home/welcome' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>参数分类</el-breadcrumb-item>
        </el-breadcrumb>

        <!-- 卡片 -->
        <el-card class="box-card">
            <el-alert
                title="注意：只允许为第三级分类设置相关参数！"
                type="warning"
                show-icon
                :closable="false">
            </el-alert>

            <!-- 选择商品分类区域 -->
            <el-row class="cat_opt">
                <el-col>
                <span>选择商品分类：</span>
                <!-- 商品分类的级联选择框 -->
                <el-cascader
                    v-model="selectedCateKeys"
                    :options="cateList"
                    :props="cateProps"
                    @change="handleChange"
                ></el-cascader>
                </el-col>
            </el-row>

            <el-tabs v-model="activeTabsName" @tab-click="handleTabsClick">
                <el-tab-pane label="动态参数" name="many">
                    <el-button type="primary" size='mini' :disabled="isBtnDisabled" @click="addDialogVisible=true" >添加参数</el-button>
                    <!-- 动态参数表格 -->
                    <el-table :data="manyTableData" border stripe style="width:100%">
                        <el-table-column header-align="center" type="expand">
                                <template slot-scope="scope">
                                    <el-tag closable v-for="(item,i) in scope.row.attr_vals" :key="i" @close="handleClose(i, scope.row)" >
                                        {{item}}
                                    </el-tag>
                                    <el-input
                                        class="input-new-tag"
                                        v-if="scope.row.inputVisible"
                                        v-model="scope.row.inputValue"
                                        ref="saveTagInput"
                                        size="small"
                                        @keyup.enter.native="handleInputConfirm(scope.row)"
                                        @blur="handleInputConfirm(scope.row)"
                                        >
                                        </el-input>
                                        <el-button v-else 
                                        class="button-new-tag" 
                                        size="small" 
                                        @click="showInput(scope.row)">+ New Tag</el-button>
                                </template>
                        </el-table-column>

                        <el-table-column align="center" label="#" type="index"></el-table-column>
                        <el-table-column prop="attr_name" label="动态参数"></el-table-column>
                        <el-table-column label="操作" width="200px">
                            <template slot-scope="scope">
                                <!-- 编辑按钮 -->
                                <el-button @click="showeditdialog(scope.row.attr_id)" type="primary" size="mini" icon="el-icon-edit">编辑</el-button>
                                <!-- 删除按钮 -->
                                <el-button @click="removeUserById(scope.row.attr_id)" type="danger" size="mini" icon="el-icon-delete">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
                <el-tab-pane label="静态参数" name="only">
                    <el-button type="primary" size='mini' :disabled="isBtnDisabled" @click="addDialogVisible=true">添加属性</el-button>
                    <!-- 静态参数表格 -->
                    <el-table :data="onlyTableData" border stripe style="width: 100%">
                        <el-table-column header-align="center" type="expand">
                            <template slot-scope="scope">
                                <el-tag closable v-for="(item,i) in scope.row.attr_vals" :key="i" @close="handleClose(i, scope.row)" >
                                    {{item}}
                                </el-tag>
                                <el-input
                                    class="input-new-tag"
                                    v-if="scope.row.inputVisible"
                                    v-model="scope.row.inputValue"
                                    ref="saveTagInput"
                                    size="small"
                                    @keyup.enter.native="handleInputConfirm(scope.row)"
                                    @blur="handleInputConfirm(scope.row)"
                                    >
                                    </el-input>
                                    <el-button v-else 
                                    class="button-new-tag" 
                                    size="small" 
                                    @click="showInput(scope.row)">+ New Tag</el-button>
                            </template>

                        </el-table-column>
                        <el-table-column align="center" label="#" type="index"></el-table-column>
                        <el-table-column prop="attr_name" label="静态参数"></el-table-column>
                        <el-table-column label="操作" width="200px">
                            <template slot-scope="scope">
                                <!-- 修改按钮 -->
                                <el-button @click="showeditdialog(scope.row.attr_id)" type="primary" size="mini" icon="el-icon-edit">编辑</el-button>
                                <!-- 删除按钮 -->
                                <el-button @click="removeUserById(scope.row.attr_id)" type="danger" size="mini" icon="el-icon-delete">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
            </el-tabs>
        </el-card>

        <!-- 添加参数的对话框 -->
        <el-dialog :title="'添加'+titleText" :visible.sync="addDialogVisible" width="50%" @close="addDialogClosed">
            <el-form :model="addFrom" :rules="addFromrules" ref="addFromrule" label-width="100px">
                <el-form-item :label="titleText" prop="attr_name">
                    <el-input v-model="addFrom.attr_name"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addParams">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 修改参数的对话框 -->
        <el-dialog :title="'修改'+titleText" :visible.sync="editDialogVisible" width="50%">
            <el-form :model="editFrom" :rules="editFromrules" ref="editFromrule" label-width="100px">
                <el-form-item :label="titleText" prop="attr_name">
                    <el-input v-model="editFrom.attr_name"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="editParams">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
export default {
    data() {
        return {
            //动态参数列表
            manyTableData:[],
            //静态参数列表
            onlyTableData:[],
            // 激活页签名称
            activeTabsName:'many',
            //级联选择框双向绑定对象
            selectedCateKeys: [],
            // 商品分类列表
            cateList: [],
            //级联选择框的配置对象
            cateProps: {
                expandTrigger: 'hover',
                value: 'cat_id',
                label: 'cat_name',
                children: 'children'
            },

            //添加参数对话框
            addDialogVisible:false,
            //添加参数表单
            addFrom:{
                attr_name:''
            },
            //表单验证规则
            addFromrules:{
                attr_name:[
                    { required: true, message: '请输入参数名称', trigger: 'blur' }
                ]
            },

            //修改参数对话框
            editDialogVisible:false,
            //添加参数表单
            editFrom:{
                attr_name:''
            },
            //表单验证规则
            editFromrules:{
                attr_name:[
                    { required: true, message: '请输入参数名称', trigger: 'blur' }
                ]
            },
        }
    },
    created () {
        this.getCateList()
    },
    computed:{
        //如果按钮需要被禁用返回true 否则返回false
        isBtnDisabled(){
            if(this.selectedCateKeys.length!==3){
                return true
            }
            return false
        },
        //当前选中的三级分类ID
        cateid(){
            if(this.selectedCateKeys.length===3){
                return this.selectedCateKeys[2];
            }
            return null
        },
        //动态计算标题属性
        titleText(){
            if(this.activeTabsName==='many'){
                return '动态参数'
            }
            return '静态参数'
        }
    },
    methods: {
        //获取所有的商品分类列表
        async getCateList () {
            const { data: res } = await this.$http.get('categories')
            if (res.meta.status !== 200) {
                return this.$message.error('获取商品数据列表失败！')
            }
            this.cateList = res.data
        },

        //级联选择框变化
        handleChange(){
            this.getParamsdata()
        },

        //tab标签点击事件
        handleTabsClick(){
            this.getParamsdata()
        },

        //获取参数列表数据
       async getParamsdata(){
            //证明选中的不是三级分类
            if(this.selectedCateKeys.length!==3){
                this.selectedCateKeys=[];
                // 清空表格数据
                this.manyTableData = []
                this.onlyTableData = []
                return
            }
            
            //根据所选的分类id 和当前所处的面板，获取对应的参数
            const{data:res}=await this.$http.get(`categories/${this.cateid}/attributes`,{params:{sel:this.activeTabsName}})
            if(res.meta.status!==200){ return this.$message.error('获取参数列表失败') }
            
            res.data.forEach(element => {
                //通过三元表达式判断attr_vals是否为空
                element.attr_vals=element.attr_vals ? element.attr_vals.split(' '):[]
                element.inputVisible=false,
                element.inputValue=''
            });

            if(this.activeTabsName=="many"){
                this.manyTableData=res.data;
            }
            else{
                this.onlyTableData=res.data;
            }
        },

        //关闭添加参数对话框
        addDialogClosed(){
            this.$refs.addFromrule.resetFields();
            this.addDialogVisible=false;
        },

        //点击添加参数
        addParams(){
            this.$refs.addFromrule.validate(async valid=>{
                if(!valid) return;
                const {data:res}=await this.$http.post(`categories/${this.cateid}/attributes`,
                    {
                        attr_name:this.addFrom.attr_name,
                        attr_sel:this.activeTabsName
                    }
                )

                if(res.meta.status!==201){
                        this.$message.error('添加参数失败')
                }
                this.$message.success('添加参数成功')
                this.addDialogVisible=false;
                this.getParamsdata();
            })
        },

        //点击修改参数
        async showeditdialog(id){
            const {data:res}=await this.$http.get(`categories/${this.cateid}/attributes/`+id,
                {
                    params:{attr_sel:this.activeTabsName}
                }
            )

            if(res.meta.status!==200){
                this.$message.error('查询参数失败')
                return
            }
            
            this.editFrom = res.data
            this.editDialogVisible = true
        },

        //修改参数
        editParams(){
            this.$refs.editFromrule.validate(async valid=>{
                if(!valid) return;
                const {data:res}=await this.$http.put(`categories/${this.cateid}/attributes/${this.editFrom.attr_id}`,
                    {
                        attr_name:this.editFrom.attr_name,
                        attr_sel:this.activeTabsName
                    }
                )

                if(res.meta.status!==200){
                    this.$message.error('修改参数失败')
                    return
                }
                this.$message.success('修改参数成功')
                this.editDialogVisible=false;
                this.getParamsdata();

            })
        },

        //删除参数
       async removeUserById(id){
           const confirmResult = await this.$confirm(
                '此操作将永久删除该参数, 是否继续?',
                '提示',
                {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
                }
            ).catch(err => err)
            if (confirmResult !== 'confirm') {
                return this.$message.info('已取消删除！')
            }
            const {data:res}=await this.$http.delete(`categories/${this.cateid}/attributes/`+id)

            if(res.meta.status!==200){
                this.$message.error('删除参数失败')
                return
            }
            this.$message.success('删除参数成功')
            this.getParamsdata();
        },

        //文本框失去焦点,或者按下Enter触发
        handleInputConfirm(row){

            if(row.inputValue.length===0){
                row.inputValue=''
                row.inputVisible=false
                return
            }

            row.attr_vals.push(row.inputValue.trim())
            row.inputValue=''
            row.inputVisible=false
            
            // 提交数据库，保存修改
            this.saveAttrVals(row)
        },

        //点击按钮显示输入框
        showInput(row){
               row.inputVisible=true;
            //让输入框自动获取焦点
            // $nextTick方法的作用：当页面元素被重新渲染之后，才会至指定回调函数中的代码
            this.$nextTick(_ => {
                this.$refs.saveTagInput.$refs.input.focus()
            })  
        },

        //提交数据库，保存修改
        async saveAttrVals(row){
            const{data:res}=await this.$http.put(`categories/${this.cateid}/attributes/${row.attr_id}`,
            {
                attr_name:row.attr_name,
                attr_sel:this.activeTabsName,
                attr_vals:row.attr_vals.join(' ')
            })

            if (res.meta.status !== 200) {
                return this.$message.error('修改参数项失败！')
            }

            this.$message.success('修改参数项成功！')
        },

        //删除参数
        handleClose(i,row){
            row.attr_vals.splice(i, 1);
            this.saveAttrVals(row)
        }
    },
}
</script>

<style lang="less" scoped>
.cat_opt {
  margin: 15px 0px;
}
.el-cascader {
  width: 25%;
}
.el-tag {
  margin: 8px;
}
.input-new-tag {
  width: 90px;
}
.button-new-tag {
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
</style>